$.fn.pagination.defaults.displayMsg = '';
$(function(){
    obj.init();
});

window.obj = new function(){
    'use strict';
    return {
        schDataGrid: null,
        studDataGrid: null,
        studParams: {},
        params: {
            loadFirstSchool: true,
            createNew: false,
            schoolId: null,
            schoolName: null,
            chargeYear: null,
            startTime: null,
            endTime: null
        },
        init: function () {
            this.params.schoolId    = xhTool.getQuery('schoolId');
            if (this.params.schoolId) {
                this.params.loadFirstSchool = false;
            }
            this.params.schoolName  = decodeURI(xhTool.getQuery('schoolName'));
            this.params.chargeYear  = xhTool.getQuery('chargeYear');
            this.params.startTime   = xhTool.getQuery('startTime');
            this.params.endTime     = xhTool.getQuery('endTime');

            this.schDataGrid  = new xhDataGrid($('#SchoolList'), 'School/getDgData', {support: 1});
            this.studDataGrid = new xhDataGrid($('#StudList'), 'Cost/getStudCharge');

            this.schDataGrid.parseToolbar().init();
            this.studDataGrid.parseToolbar()//.init()
                .activeButton(['bt_list_stud_split_unlock', 'bt_list_stud_del', 'bt_list_stud_split'], ['bt_list_stud_add', 'bt_list_stud_audit', 'bt_list_stud_pass', 'bt_list_stud_apply']);

            this.funObj().bindGridEvent();
            this.funObj().dealJump();

            this.listener();
        },
        listener: function () {
            var $this = this;
            //学校搜索
            $('#bt_list_school_search').click(function(){
                $this.funObj().schoolSearch();
            });
            //学生搜索
            $('#bt_list_stud_search').click(function(){
                $this.funObj().studSearch();
            });
            //新增缴费
            $('#bt_list_stud_add').click(function(){
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().chargeAdd();
            });
            //导入缴费信息文件
            $('#bt_list_stud_import').click(function(){
                $this.funObj().chargeImport(1);
            });
            //拆分付费信息
            $('#bt_list_stud_split').click(function(){
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().chargeSplit();
            });
            //一键拆分
            $('#bt_list_stud_split_all').click(function(){
                $this.funObj().chargeSplitAll();
            });
            //申请修改
            $('#bt_list_stud_apply').click(function(){
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().changeState(2, '提交修改申请？');
            });
            //申请通过
            $('#bt_list_stud_pass').click(function(){
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().changeState(3, '更改为可修改状态？');
            });
            //审核通过
            $('#bt_list_stud_audit').click(function(){
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().changeState(1, '确认审核通过？');
            });
            //解锁拆分
            $('#bt_list_stud_split_unlock').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().changeSplitLock();
            });
            //删除
            $('#bt_list_stud_del').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().delChargeRecord();
            });
            //手工导入
            $('#bt_list_stud_hand_import').click(function () {
                $this.funObj().chargeImport(2);
            });
            //流水导入
            $('#bt_list_stud_journal_import').click(function () {
                $this.funObj().chargeImport(3);
            });
            //导出
            $('#bt_list_stud_export').click(function () {
                $('#bt_list_stud_search').click();
                location.href = baseUrl + 'Cost/exportStudCharge?' + xhTool.parseParam($this.studParams);
            });
        },
        funObj: function(){
            var $this = this;
            return {
                bindGridEvent: function() {
                    $this.schDataGrid.onSelect = function(rowIndex, rowData){
                        $this.studParams.schoolId = rowData.iSchoolId;
                        $this.funObj().studSearch();
                        // $this.studDataGrid.reload($this.studParams);
                        $this.studDataGrid.setTitle(null, '-' + rowData.sSchoolName);
                    };
                    $this.schDataGrid.onLoadSuccess = function(data){
                        if(data['rows'].length <= 0){
                            return false;
                        }
                        if ($this.params.loadFirstSchool) {
                            $this.schDataGrid.command('selectRow', 0);
                        }
                    };

                    $this.studDataGrid.onLoadSuccess = function(){
                        $this.studDataGrid.clear();
                    };
                    $this.studDataGrid.onDblClickRow = function(rowIndex, rowData){
                        if (!rowData.iCCId) {
                            return false;
                        }
                        window.top.xhTop.showModal({
                            title: '修改缴费-' + rowData.sUserName,
                            content: xhTool.getFrameString('Cost/studChargeModify', {type: 'modify', id: rowData.iCCId}, 450),
                            size: 'sm',
                            button: '确认',
                            backClose: false
                        });
                    };
                },
                schoolSearch: function () {
                    $this.schDataGrid.reload({
                        search: {
                            vague: xhExtra.getValue($('#list_school_vague'))
                        }
                    });
                },
                studSearch: function () {
                    $this.studParams.chargeYear = xhExtra.getValue($('#list_stud_year'));
                    $this.studParams.isCharge   = xhExtra.getValue($('#list_stud_charge'));
                    $this.studParams.costTarget = xhExtra.getValue($('#list_stud_cost_target'));
                    $this.studParams.search     = {vague: xhExtra.getValue($('#list_stud_vague'))};
                    $this.studParams.className  = xhExtra.getValue($('#list_stud_class'));
                    $this.studParams.timeType  = xhExtra.getValue($('#list_time_type'));
                    $this.studParams.startTime  = xhExtra.getValue($('#list_startTime'));
                    $this.studParams.endTime    = xhExtra.getValue($('#list_endTime'));
                    $this.studParams.history    = xhExtra.getValue($('#list_stud_history'));
                    $this.studDataGrid.reload($this.studParams);
                },
                dealJump: function () {
                    if (!$this.params.schoolId) {
                        return false;
                    }
                    $this.studParams.schoolId = $this.params.schoolId;
                    // $this.params.schoolId = null;
                    $('#list_stud_year').combobox('setValue', $this.params.chargeYear || '');
                    $('#list_startTime').datebox('setValue', $this.params.startTime);
                    $('#list_endTime').datebox('setValue', $this.params.endTime);
                    $('#list_stud_class').textbox('setValue', xhTool.getQuery('grade'));
                    $this.funObj().studSearch();
                    $this.studDataGrid.setTitle(null, '-' + $this.params.schoolName);
                },
                chargeAdd: function () {
                    var rowData = $this.studDataGrid.getSelectValue(true);
                    window.top.xhTop.showModal({
                        title: '新增缴费-' + rowData.sUserName,
                        content: xhTool.getFrameString('Cost/studChargeModify', {type: 'create', studId: rowData.iUserId}, 530),
                        size: 'sm',
                        button: '确认',
                        backClose: false
                    });
                },
                chargeImport: function (type) {
                    $this.params.createNew = false;
                    $this.params.autoClass = 0;
                    window.top.swal.setDefaults({
                        title: $this.schDataGrid.getSelectValue('sSchoolName'),
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: type === 1 ? ['1', '2', '3', '4'] : ['1', '2']
                    });
                    var chargeYear,
                        stepTemp = [
                        {
                            text: '输入缴费年度',
                            input: 'number',
                            confirmButtonText: '下一步',
                            preConfirm: function(year) {
                                return new Promise(function (resolve, reject) {
                                    if (year < 2000 || year > 2100) {
                                        reject('缴费年份不正确！');
                                    } else {
                                        chargeYear = year;
                                        resolve();
                                    }
                                })
                            }
                        },
                        {
                            text: '是否新增账号，无账号时自动创建账号',
                            confirmButtonText: '是',
                            cancelButtonText: '否',
                            preConfirm: function(year) {
                                return new Promise(function (resolve, reject) {
                                    $this.params.createNew = true;
                                    resolve();
                                })
                            }
                        },
                        {
                            text: '自动创建班级',
                            input: 'select',
                            inputOptions: {
                                1: '行政班',
                                // 2: '培优班'
                            },
                            confirmButtonText: '确认',
                            showCancelButton: false,
                            preConfirm: function(autoClass) {
                                return new Promise(function (resolve, reject) {
                                    $this.params.autoClass = autoClass;
                                    resolve();
                                })
                            }
                        },
                        {
                            text: '导入excel文件',
                            input: 'file',
                            inputAttributes: {accept: '.xls,.xlsx'},
                            confirmButtonText: '导入',
                            preConfirm: function(file) {
                                return new Promise(function (resolve, reject) {
                                    if (!file) {
                                        reject('文件不能为空！');
                                    } else {
                                        window.top.swal.resetDefaults();
                                        var fileData = new FormData();
                                        fileData.append('chargeYear', chargeYear);
                                        fileData.append('file', file);
                                        fileData.append('type', type);
                                        fileData.append('schoolId', $this.studParams.schoolId);
                                        fileData.append('createNew', $this.params.createNew);
                                        fileData.append('autoClass', $this.params.autoClass);
                                        $.ajax({
                                            url: baseUrl + 'Cost/importChargeFile',
                                            type: 'POST',
                                            processData: false,
                                            contentType: false,
                                            data: fileData,
                                            complete: function(XMLHttpRequest){
                                                var result = XMLHttpRequest.responseJSON;
                                                if(xhExtra.checkError(result)) return false;
                                                if (result.errorData.length > 0){
                                                    var content = '';
                                                    // if (type) {
                                                    //     $.each(result.errorData, function(index, row){
                                                    //         content += '<tr><td>' + row.name + '</td><td>' + row.reason + '</td></tr>';
                                                    //     });
                                                    //     window.top.swal({
                                                    //         title: result.msg,
                                                    //         type: 'warning',
                                                    //         html: '<table class="table table-striped"><tr>' +
                                                    //         '<th style="text-align: center">学生</th>' +
                                                    //         '<th style="text-align: center">原因</th>' +
                                                    //         '</tr>' + content + '</table>'
                                                    //     });
                                                    // }
                                                    // else {
                                                        $.each(result.errorData, function(index, row){
                                                            // content += `<tr><td>${row.name}</td><td>${row.code}</td><td>${row.reason}</td></tr>`;
                                                            content += '<tr><td>' + row.name + '</td><td>' + row.code + '</td><td>' + row.reason + '</td></tr>';
                                                        });
                                                        window.top.swal({
                                                            title: result.msg,
                                                            type: 'warning',
                                                            html: '<table class="table table-striped"><tr>' +
                                                            '<th style="text-align: center">学生</th>' +
                                                            '<th style="text-align: center">缴费编号</th>' +
                                                            '<th style="text-align: center">原因</th>' +
                                                            '</tr>' + content + '</table>'
                                                        });
                                                    // }
                                                }
                                                else{
                                                    window.top.xhTop.showSuccess(result.msg);
                                                }
                                                $this.studDataGrid.reload();
                                            }
                                        });
                                        // var reader = new FileReader();
                                        // reader.onload = function (e) {
                                        //     $.ajax({
                                        //         url: baseUrl + 'Cost/importChargeFile',
                                        //         type: 'POST',
                                        //         data: {fileString: e.target.result, fileName: file.name, chargeYear: chargeYear},
                                        //         complete: function(XMLHttpRequest){
                                        //             var result = XMLHttpRequest.responseJSON;
                                        //             if(xhExtra.checkError(result)) return false;
                                        //             if (result.errorData.length > 0){
                                        //                 var content = '';
                                        //                 $.each(result.errorData, function(index, row){
                                        //                     // content += `<tr><td>${row.name}</td><td>${row.code}</td><td>${row.reason}</td></tr>`;
                                        //                     content += '<tr><td>' + row.name + '</td><td>' + row.code + '</td><td>' + row.reason + '</td></tr>';
                                        //                 });
                                        //                 window.top.swal({
                                        //                     title: result.msg,
                                        //                     type: 'warning',
                                        //                     html: '<table class="table table-striped"><tr>' +
                                        //                         '<th style="text-align: center">学生</th>' +
                                        //                         '<th style="text-align: center">缴费编号</th>' +
                                        //                         '<th style="text-align: center">原因</th>' +
                                        //                     '</tr>' + content + '</table>'
                                        //                 });
                                        //             }
                                        //             else{
                                        //                 window.top.xhTop.showMessage({type: 'success', title: result.msg});
                                        //             }
                                        //             $this.studDataGrid.reload();
                                        //         }
                                        //     });
                                        // };
                                        // reader.readAsDataURL(file);
                                    }
                                })
                            }
                        }
                    ];
                    var steps;
                    if (type === 1) {
                        steps = stepTemp;
                    }
                    else {
                        steps = [stepTemp[0], stepTemp[3]];
                    }


                    window.top.swal.queue(steps).then(function(result) {}, function(dismiss) {window.top.swal.resetDefaults();});
                },
                chargeSplit: function () {
                    // var rowData = $this.studDataGrid.getSelectValue(true);
                    // if (!rowData.iCCId) {
                    //     window.top.xhTop.showMessage({type: 'error', title: '该记录无缴费信息！'});
                    //     return false;
                    // }
                    // window.top.xhTop.showModal({
                    //     title: '拆分缴费-' + rowData.sUserName,
                    //     content: xhTool.getFrameString('Cost/studChargeModify', {type: 'split', id: rowData.iCCId}, 400),
                    //     size: 'sm',
                    //     button: '确认',
                    //     backClose: false
                    // });
                    var sourceIds = $this.studDataGrid.getSelectValues('iCCId');
                    var ids = xhTool.clearNullArr(sourceIds);
                    if (sourceIds.length !== ids.length || ids.length <= 0) {
                        window.top.xhTop.showError('选中记录中含无缴费记录！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '拆分缴费-' + ids.length + '人',
                        content: xhTool.getFrameString('Cost/studChargeModify', {type: 'split', ids: ids.join(',')}, 530),
                        size: 'sm',
                        button: '确认',
                        backClose: false
                    });
                },
                chargeSplitAll: function () {
                    window.top.xhTop.showModal({
                        title: '一键拆分-' + $this.schDataGrid.getSelectValue('sSchoolName'),
                        content: xhTool.getFrameString('Cost/studChargeModify',
                            {type: 'splitAll', schoolId:  $this.schDataGrid.getSelectValue('iSchoolId')}, 530),
                        size: 'sm',
                        button: '确认',
                        backClose: false
                    });
                },
                changeState: function (_state, _msg) {
                    var rowData = $this.studDataGrid.getSelectValue(true);
                    if (!rowData.iCCId) {
                        window.top.xhTop.showMessage({type: 'error', title: '该记录无缴费信息！'});
                        return false;
                    }
                    if (rowData.bImport === '导入') {
                        window.top.xhTop.showMessage({type: 'error', title: '导入数据不可操作！'});
                        return false;
                    }
                    xhExtra.askChangeStatus('Cost/modifyStudChargeState', {id: rowData.iCCId, state: _state}, $this.studDataGrid, _msg);
                },
                changeSplitLock: function () {
                    var ids = $this.studDataGrid.getSelectValues('iCCId');
                    xhExtra.askChangeStatus('Cost/unlockStudChargeSplit', {ids: ids}, $this.studDataGrid, '确认解锁？');
                },
                delChargeRecord: function () {
                    var ids = xhTool.clearNullArr($this.studDataGrid.getSelectValues('iCCId'));
                    if (!ids) {
                        window.top.xhTop.showError('无缴费记录选中！');
                        return false;
                    }
                    xhExtra.askChangeStatus('Cost/delStudCharge', {ids: ids}, $this.studDataGrid, '是否确认删除？');
                }
            }
        }
    }
}